package com.xlh.virtualization.controller;

import com.xlh.common.Result;
import com.xlh.exception.common.GlobalException;
import com.xlh.security.UserInfoHolder;
import com.xlh.virtualization.domain.Image;
import com.xlh.virtualization.po.ImageSavePO;
import com.xlh.virtualization.service.ImageAllocationImageService;
import com.xlh.virtualization.service.ImageService;
import com.xlh.vo.CascaderVO;
import com.xlh.virtualization.vo.ImageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

import static com.xlh.virtualization.constant.ImageConstant.SYSTEM_PRESET_CODE;
import static com.xlh.virtualization.constant.ImageConstant.TEACHER_MADE_CODE;

/**
 * @author cheer
 */
@Api("镜像分配流程镜像相关操作")
@RestController
@RequestMapping("/image-allocation/image")
public class ImageAllocationImageController {

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Autowired
    private ImageAllocationImageService imageAllocationImageService;

    @Autowired
    private ImageService imageService;

    @ApiOperation("镜像分配时查询用户可见的镜像列表")
    @GetMapping
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result<List<CascaderVO>> listImages(@RequestParam Boolean cluster) {
        // 当前业务下集群模式不允许选择gpu镜像
        boolean excludeGpu = cluster;

        List<Image> images;
        if (userInfoHolder.isTeacher()) {
            images = imageAllocationImageService.listTeacherVisibleImages(userInfoHolder.getUserId(), excludeGpu);
        } else {
            images = imageAllocationImageService.listAdminVisibleImages(excludeGpu);
        }

        List<CascaderVO> cascaderVOS = new ArrayList<>();
        // 系统预置的分类
        CascaderVO systemPreset = CascaderVO.builder()
                .value((long) SYSTEM_PRESET_CODE)
                .label("系统预置")
                .children(new ArrayList<>())
                .build();
        // 教师制作的分类
        CascaderVO teacherMade = CascaderVO.builder()
                .value((long) TEACHER_MADE_CODE)
                .label("教师制作")
                .children(new ArrayList<>())
                .build();
        // 将镜像放置对应的分类中
        if (CollectionUtils.isNotEmpty(images)) {
            for (Image image : images) {
                CascaderVO cascader = CascaderVO.builder()
                        .value(image.getId())
                        .label(image.getGpu() ? image.getImageName() + "（GPU）" : image.getImageName())
                        .build();
                if (image.getImageSource() == SYSTEM_PRESET_CODE) {
                    systemPreset.getChildren().add(cascader);
                } else if (image.getImageSource() == TEACHER_MADE_CODE) {
                    teacherMade.getChildren().add(cascader);
                }
            }
        }
        cascaderVOS.add(systemPreset);
        cascaderVOS.add(teacherMade);

        return Result.success(cascaderVOS);
    }

    @ApiOperation("保存镜像")
    @PostMapping
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result<Long> saveImage(@RequestBody @Valid ImageSavePO imageSavePO) {
        Long imageId = imageAllocationImageService.saveImage(userInfoHolder.getUserId(), userInfoHolder.isAdmin(), imageSavePO);
        return Result.success(imageId);
    }

    @ApiOperation("查询镜像")
    @GetMapping("/{imageId}")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result<ImageVO> queryImage(@PathVariable("imageId") Long imageId) {
        ImageVO imageVO = imageService.getImageById(imageId, userInfoHolder.isSuperAdmin());
        if (imageVO == null) {
            throw new GlobalException("镜像不存在");
        }
        return Result.success(imageVO);
    }

    @ApiOperation("覆盖镜像")
    @PutMapping("/{imageId}")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result coverImage(@PathVariable("imageId") Long imageId,
                             @RequestBody @Valid ImageSavePO imageSavePO) {
        imageAllocationImageService.coverImage(userInfoHolder.getUserId(), imageId, imageSavePO);
        return Result.success();
    }

    @ApiOperation("查询镜像是否为当前用户创建的")
    @GetMapping("/{imageId}/self")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result<Boolean> isImageOwner(@PathVariable("imageId") Long imageId) {
        Boolean isSelf = imageAllocationImageService.isImageOwner(imageId, userInfoHolder.getUserId());
        return Result.success(isSelf);
    }

}
